home *** CD-ROM | disk | FTP | other *** search
/ Scene Storm / Scene Storm - Volume 1.iso / coding / c / jpeglib5b / djpeg.c < prev    next >
C/C++ Source or Header  |  1980-01-12  |  23KB  |  751 lines

  1. /*
  2.  * djpeg.c
  3.  *
  4.  * Copyright (C) 1991-1994, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains a command-line user interface for the JPEG decompressor.
  9.  * It should work on any system with Unix- or MS-DOS-style command lines.
  10.  *
  11.  * Two different command line styles are permitted, depending on the
  12.  * compile-time switch TWO_FILE_COMMANDLINE:
  13.  *    djpeg [options]  inputfile outputfile
  14.  *    djpeg [options]  [inputfile]
  15.  * In the second style, output is always to standard output, which you'd
  16.  * normally redirect to a file or pipe to some other program.  Input is
  17.  * either from a named file or from standard input (typically redirected).
  18.  * The second style is convenient on Unix but is unhelpful on systems that
  19.  * don't support pipes.  Also, you MUST use the first style if your system
  20.  * doesn't do binary I/O to stdin/stdout.
  21.  * To simplify script writing, the "-outfile" switch is provided.  The syntax
  22.  *    djpeg [options]  -outfile outputfile  inputfile
  23.  * works regardless of which command line style is used.
  24.  */
  25.  
  26. #include "cdjpeg.h"        /* Common decls for cjpeg/djpeg applications */
  27. #include "jversion.h"        /* for version message */
  28.  
  29. #include <ctype.h>        /* to declare isupper(),tolower(),isprint() */
  30. #ifdef NEED_SIGNAL_CATCHER
  31. #include <signal.h>        /* to declare signal() */
  32. #endif
  33. #ifdef USE_SETMODE
  34. #include <fcntl.h>        /* to declare setmode()'s parameter macros */
  35. /* If you have setmode() but not <io.h>, just delete this line: */
  36. #include <io.h>            /* to declare setmode() */
  37. #endif
  38.  
  39. #ifdef USE_CCOMMAND        /* command-line reader for Macintosh */
  40. #ifdef __MWERKS__
  41. #include <SIOUX.h>              /* Metrowerks declares it here */
  42. #endif
  43. #ifdef THINK_C
  44. #include <console.h>        /* Think declares it here */
  45. #endif
  46. #endif
  47.  
  48. #ifdef DONT_USE_B_MODE        /* define mode parameters for fopen() */
  49. #define READ_BINARY    "r"
  50. #define WRITE_BINARY    "w"
  51. #else
  52. #define READ_BINARY    "rb"
  53. #define WRITE_BINARY    "wb"
  54. #endif
  55.  
  56. #ifndef EXIT_FAILURE        /* define exit() codes if not provided */
  57. #define EXIT_FAILURE  1
  58. #endif
  59. #ifndef EXIT_SUCCESS
  60. #ifdef VMS
  61. #define EXIT_SUCCESS  1        /* VMS is very nonstandard */
  62. #else
  63. #define EXIT_SUCCESS  0
  64. #endif
  65. #endif
  66. #ifndef EXIT_WARNING
  67. #ifdef VMS
  68. #define EXIT_WARNING  1        /* VMS is very nonstandard */
  69. #else
  70. #define EXIT_WARNING  2
  71. #endif
  72. #endif
  73.  
  74.  
  75. /* Create the add-on message string table. */
  76.  
  77. #define JMESSAGE(code,string)    string ,
  78.  
  79. static const char * const cdjpeg_message_table[] = {
  80. #include "cderror.h"
  81.   NULL
  82. };
  83.  
  84.  
  85. /*
  86.  * This list defines the known output image formats
  87.  * (not all of which need be supported by a given version).
  88.  * You can change the default output format by defining DEFAULT_FMT;
  89.  * indeed, you had better do so if you undefine PPM_SUPPORTED.
  90.  */
  91.  
  92. typedef enum {
  93.     FMT_BMP,        /* BMP format (Windows flavor) */
  94.     FMT_GIF,        /* GIF format */
  95.     FMT_OS2,        /* BMP format (OS/2 flavor) */
  96.     FMT_PPM,        /* PPM/PGM (PBMPLUS formats) */
  97.     FMT_RLE,        /* RLE format */
  98.     FMT_TARGA,        /* Targa format */
  99.     FMT_TIFF        /* TIFF format */
  100. } IMAGE_FORMATS;
  101.  
  102. #ifndef DEFAULT_FMT        /* so can override from CFLAGS in Makefile */
  103. #define DEFAULT_FMT    FMT_PPM
  104. #endif
  105.  
  106. static IMAGE_FORMATS requested_fmt;
  107.  
  108.  
  109. /*
  110.  * Signal catcher to ensure that temporary files are removed before aborting.
  111.  * NB: for Amiga Manx C this is actually a global routine named _abort();
  112.  * we put "#define signal_catcher _abort" in jconfig.h.  Talk about bogus...
  113.  */
  114.  
  115. #ifdef NEED_SIGNAL_CATCHER
  116.  
  117. static j_common_ptr sig_cinfo;
  118.  
  119. GLOBAL void
  120. signal_catcher (int signum)
  121. {
  122.   if (sig_cinfo != NULL) {
  123.     if (sig_cinfo->err != NULL) /* turn off trace output */
  124.       sig_cinfo->err->trace_level = 0;
  125.     jpeg_destroy(sig_cinfo);    /* clean up memory allocation & temp files */
  126.   }
  127.   exit(EXIT_FAILURE);
  128. }
  129.  
  130. #endif
  131.  
  132.  
  133. /*
  134.  * Optional routine to display a percent-done figure on stderr.
  135.  */
  136.  
  137. #ifdef PROGRESS_REPORT
  138.  
  139. METHODDEF void
  140. progress_monitor (j_common_ptr cinfo)
  141. {
  142.   cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress;
  143.   int total_passes = prog->pub.total_passes + prog->total_extra_passes;
  144.   int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit);
  145.  
  146.   if (percent_done != prog->percent_done) {
  147.     prog->percent_done = percent_done;
  148.     if (total_passes > 1) {
  149.       fprintf(stderr, "\rPass %d/%d: %3d%% ",
  150.           prog->pub.completed_passes + prog->completed_extra_passes + 1,
  151.           total_passes, percent_done);
  152.     } else {
  153.       fprintf(stderr, "\r %3d%% ", percent_done);
  154.     }
  155.     fflush(stderr);
  156.   }
  157. }
  158.  
  159. #endif
  160.  
  161.  
  162. /*
  163.  * Argument-parsing code.
  164.  * The switch parser is designed to be useful with DOS-style command line
  165.  * syntax, ie, intermixed switches and file names, where only the switches
  166.  * to the left of a given file name affect processing of that file.
  167.  * The main program in this file doesn't actually use this capability...
  168.  */
  169.  
  170.  
  171. static const char * progname;    /* program name for error messages */
  172. static char * outfilename;    /* for -outfile switch */
  173.  
  174.  
  175. LOCAL void
  176. usage (void)
  177. /* complain about bad command line */
  178. {
  179.   fprintf(stderr, "usage: %s [switches] ", progname);
  180. #ifdef TWO_FILE_COMMANDLINE
  181.   fprintf(stderr, "inputfile outputfile\n");
  182. #else
  183.   fprintf(stderr, "[inputfile]\n");
  184. #endif
  185.  
  186.   fprintf(stderr, "Switches (names may be abbreviated):\n");
  187.   fprintf(stderr, "  -colors N      Reduce image to no more than N colors\n");
  188.   fprintf(stderr, "  -fast          Fast, low-quality processing\n");
  189.   fprintf(stderr, "  -grayscale     Force grayscale output\n");
  190. #ifdef IDCT_SCALING_SUPPORTED
  191.   fprintf(stderr, "  -scale M/N     Scale output image by fraction M/N, eg, 1/8\n");
  192. #endif
  193. #ifdef BMP_SUPPORTED
  194.   fprintf(stderr, "  -bmp           Select BMP output format (Windows style)%s\n",
  195.       (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
  196. #endif
  197. #ifdef GIF_SUPPORTED
  198.   fprintf(stderr, "  -gif           Select GIF output format%s\n",
  199.       (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
  200. #endif
  201. #ifdef BMP_SUPPORTED
  202.   fprintf(stderr, "  -os2           Select BMP output format (OS/2 style)%s\n",
  203.       (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
  204. #endif
  205. #ifdef PPM_SUPPORTED
  206.   fprintf(stderr, "  -pnm           Select PBMPLUS (PPM/PGM) output format%s\n",
  207.       (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
  208. #endif
  209. #ifdef RLE_SUPPORTED
  210.   fprintf(stderr, "  -rle           Select Utah RLE output format%s\n",
  211.       (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
  212. #endif
  213. #ifdef TARGA_SUPPORTED
  214.   fprintf(stderr, "  -targa         Select Targa output format%s\n",
  215.       (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
  216. #endif
  217.   fprintf(stderr, "Switches for advanced users:\n");
  218. #ifdef DCT_ISLOW_SUPPORTED
  219.   fprintf(stderr, "  -dct int       Use integer DCT method%s\n",
  220.       (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
  221. #endif
  222. #ifdef DCT_IFAST_SUPPORTED
  223.   fprintf(stderr, "  -dct fast      Use fast integer DCT (less accurate)%s\n",
  224.       (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
  225. #endif
  226. #ifdef DCT_FLOAT_SUPPORTED
  227.   fprintf(stderr, "  -dct float     Use floating-point DCT method%s\n",
  228.       (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
  229. #endif
  230.   fprintf(stderr, "  -dither fs     Use F-S dithering (default)\n");
  231.   fprintf(stderr, "  -dither none   Don't use dithering in quantization\n");
  232.   fprintf(stderr, "  -dither ordered  Use ordered dither (medium speed, quality)\n");
  233. #ifdef QUANT_2PASS_SUPPORTED
  234.   fprintf(stderr, "  -map FILE      Map to colors used in named image file\n");
  235. #endif
  236.   fprintf(stderr, "  -nosmooth      Don't use high-quality upsampling\n");
  237. #ifdef QUANT_1PASS_SUPPORTED
  238.   fprintf(stderr, "  -onepass       Use 1-pass quantization (fast, low quality)\n");
  239. #endif
  240.   fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
  241.   fprintf(stderr, "  -outfile name  Specify name for output file\n");
  242.   fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
  243.   exit(EXIT_FAILURE);
  244. }
  245.  
  246.  
  247. LOCAL boolean
  248. keymatch (char * arg, const char * keyword, int minchars)
  249. /* Case-insensitive matching of (possibly abbreviated) keyword switches. */
  250. /* keyword is the constant keyword (must be lower case already), */
  251. /* minchars is length of minimum legal abbreviation. */
  252. {
  253.   register int ca, ck;
  254.   register int nmatched = 0;
  255.  
  256.   while ((ca = *arg++) != '\0') {
  257.     if ((ck = *keyword++) == '\0')
  258.       return FALSE;        /* arg longer than keyword, no good */
  259.     if (isupper(ca))        /* force arg to lcase (assume ck is already) */
  260.       ca = tolower(ca);
  261.     if (ca != ck)
  262.       return FALSE;        /* no good */
  263.     nmatched++;            /* count matched characters */
  264.   }
  265.   /* reached end of argument; fail if it's too short for unique abbrev */
  266.   if (nmatched < minchars)
  267.     return FALSE;
  268.   return TRUE;            /* A-OK */
  269. }
  270.  
  271.  
  272. LOCAL int
  273. parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
  274.         int last_file_arg_seen, boolean for_real)
  275. /* Parse optional switches.
  276.  * Returns argv[] index of first file-name argument (== argc if none).
  277.  * Any file names with indexes <= last_file_arg_seen are ignored;
  278.  * they have presumably been processed in a previous iteration.
  279.  * (Pass 0 for last_file_arg_seen on the first or only iteration.)
  280.  * for_real is FALSE on the first (dummy) pass; we may skip any expensive
  281.  * processing.
  282.  */
  283. {
  284.   int argn;
  285.   char * arg;
  286.  
  287.   /* Set up default JPEG parameters. */
  288.   requested_fmt = DEFAULT_FMT;    /* set default output file format */
  289.   outfilename = NULL;
  290.   cinfo->err->trace_level = 0;
  291.  
  292.   /* Scan command line options, adjust parameters */
  293.  
  294.   for (argn = 1; argn < argc; argn++) {
  295.     arg = argv[argn];
  296.     if (*arg != '-') {
  297.       /* Not a switch, must be a file name argument */
  298.       if (argn <= last_file_arg_seen) {
  299.     outfilename = NULL;    /* -outfile applies to just one input file */
  300.     continue;        /* ignore this name if previously processed */
  301.       }
  302.       break;            /* else done parsing switches */
  303.     }
  304.     arg++;            /* advance past switch marker character */
  305.  
  306.     if (keymatch(arg, "bmp", 1)) {
  307.       /* BMP output format. */
  308.       requested_fmt = FMT_BMP;
  309.  
  310.     } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
  311.            keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
  312.       /* Do color quantization. */
  313.       int val;
  314.  
  315.       if (++argn >= argc)    /* advance to next argument */
  316.     usage();
  317.       if (sscanf(argv[argn], "%d", &val) != 1)
  318.     usage();
  319.       cinfo->desired_number_of_colors = val;
  320.       cinfo->quantize_colors = TRUE;
  321.  
  322.     } else if (keymatch(arg, "dct", 2)) {
  323.       /* Select IDCT algorithm. */
  324.       if (++argn >= argc)    /* advance to next argument */
  325.     usage();
  326.       if (keymatch(argv[argn], "int", 1)) {
  327.     cinfo->dct_method = JDCT_ISLOW;
  328.       } else if (keymatch(argv[argn], "fast", 2)) {
  329.     cinfo->dct_method = JDCT_IFAST;
  330.       } else if (keymatch(argv[argn], "float", 2)) {
  331.     cinfo->dct_method = JDCT_FLOAT;
  332.       } else
  333.     usage();
  334.  
  335.     } else if (keymatch(arg, "dither", 2)) {
  336.       /* Select dithering algorithm. */
  337.       if (++argn >= argc)    /* advance to next argument */
  338.     usage();
  339.       if (keymatch(argv[argn], "fs", 2)) {
  340.     cinfo->dither_mode = JDITHER_FS;
  341.       } else if (keymatch(argv[argn], "none", 2)) {
  342.     cinfo->dither_mode = JDITHER_NONE;
  343.       } else if (keymatch(argv[argn], "ordered", 2)) {
  344.     cinfo->dither_mode = JDITHER_ORDERED;
  345.       } else
  346.     usage();
  347.  
  348.     } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
  349.       /* Enable debug printouts. */
  350.       /* On first -d, print version identification */
  351.       static boolean printed_version = FALSE;
  352.  
  353.       if (! printed_version) {
  354.     fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n",
  355.         JVERSION, JCOPYRIGHT);
  356.     printed_version = TRUE;
  357.       }
  358.       cinfo->err->trace_level++;
  359.  
  360.     } else if (keymatch(arg, "fast", 1)) {
  361.       /* Select recommended processing options for quick-and-dirty output. */
  362.       cinfo->two_pass_quantize = FALSE;
  363.       cinfo->dither_mode = JDITHER_ORDERED;
  364.       if (! cinfo->quantize_colors) /* don't override an earlier -colors */
  365.     cinfo->desired_number_of_colors = 216;
  366.       cinfo->dct_method = JDCT_FASTEST;
  367.       cinfo->do_fancy_upsampling = FALSE;
  368.  
  369.     } else if (keymatch(arg, "gif", 1)) {
  370.       /* GIF output format. */
  371.       requested_fmt = FMT_GIF;
  372.  
  373.     } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
  374.       /* Force monochrome output. */
  375.       cinfo->out_color_space = JCS_GRAYSCALE;
  376.  
  377.     } else if (keymatch(arg, "map", 3)) {
  378.       /* Quantize to a color map taken from an input file. */
  379.       if (++argn >= argc)    /* advance to next argument */
  380.     usage();
  381.       if (for_real) {        /* too expensive to do twice! */
  382. #ifdef QUANT_2PASS_SUPPORTED    /* otherwise can't quantize to supplied map */
  383.     FILE * mapfile;
  384.  
  385.     if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
  386.       fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
  387.       exit(EXIT_FAILURE);
  388.     }
  389.     read_color_map(cinfo, mapfile);
  390.     fclose(mapfile);
  391.     cinfo->quantize_colors = TRUE;
  392. #else
  393.     ERREXIT(cinfo, JERR_NOT_COMPILED);
  394. #endif
  395.       }
  396.  
  397.     } else if (keymatch(arg, "maxmemory", 3)) {
  398.       /* Maximum memory in Kb (or Mb with 'm'). */
  399.       long lval;
  400.       char ch = 'x';
  401.  
  402.       if (++argn >= argc)    /* advance to next argument */
  403.     usage();
  404.       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  405.     usage();
  406.       if (ch == 'm' || ch == 'M')
  407.     lval *= 1000L;
  408.       cinfo->mem->max_memory_to_use = lval * 1000L;
  409.  
  410.     } else if (keymatch(arg, "nosmooth", 3)) {
  411.       /* Suppress fancy upsampling */
  412.       cinfo->do_fancy_upsampling = FALSE;
  413.  
  414.     } else if (keymatch(arg, "onepass", 3)) {
  415.       /* Use fast one-pass quantization. */
  416.       cinfo->two_pass_quantize = FALSE;
  417.  
  418.     } else if (keymatch(arg, "os2", 3)) {
  419.       /* BMP output format (OS/2 flavor). */
  420.       requested_fmt = FMT_OS2;
  421.  
  422.     } else if (keymatch(arg, "outfile", 4)) {
  423.       /* Set output file name. */
  424.       if (++argn >= argc)    /* advance to next argument */
  425.     usage();
  426.       outfilename = argv[argn];    /* save it away for later use */
  427.  
  428.     } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
  429.       /* PPM/PGM output format. */
  430.       requested_fmt = FMT_PPM;
  431.  
  432.     } else if (keymatch(arg, "rle", 1)) {
  433.       /* RLE output format. */
  434.       requested_fmt = FMT_RLE;
  435.  
  436.     } else if (keymatch(arg, "scale", 1)) {
  437.       /* Scale the output image by a fraction M/N. */
  438.       if (++argn >= argc)    /* advance to next argument */
  439.     usage();
  440.       if (sscanf(argv[argn], "%d/%d",
  441.          &cinfo->scale_num, &cinfo->scale_denom) != 2)
  442.     usage();
  443.  
  444.     } else if (keymatch(arg, "targa", 1)) {
  445.       /* Targa output format. */
  446.       requested_fmt = FMT_TARGA;
  447.  
  448.     } else {
  449.       usage();            /* bogus switch */
  450.     }
  451.   }
  452.  
  453.   return argn;            /* return index of next arg (file name) */
  454. }
  455.  
  456.  
  457. /*
  458.  * Marker processor for COM markers.
  459.  * This replaces the library's built-in processor, which just skips the marker.
  460.  * We want to print out the marker as text, if possible.
  461.  * Note this code relies on a non-suspending data source.
  462.  */
  463.  
  464. LOCAL unsigned int
  465. jpeg_getc (j_decompress_ptr cinfo)
  466. /* Read next byte */
  467. {
  468.   struct jpeg_source_mgr * datasrc = cinfo->src;
  469.  
  470.   if (datasrc->bytes_in_buffer == 0) {
  471.     if (! (*datasrc->fill_input_buffer) (cinfo))
  472.       ERREXIT(cinfo, JERR_CANT_SUSPEND);
  473.   }
  474.   datasrc->bytes_in_buffer--;
  475.   return GETJOCTET(*datasrc->next_input_byte++);
  476. }
  477.  
  478.  
  479. METHODDEF boolean
  480. COM_handler (j_decompress_ptr cinfo)
  481. {
  482.   boolean traceit = (cinfo->err->trace_level >= 1);
  483.   INT32 length;
  484.   unsigned int ch;
  485.   unsigned int lastch = 0;
  486.  
  487.   length = jpeg_getc(cinfo) << 8;
  488.   length += jpeg_getc(cinfo);
  489.   length -= 2;            /* discount the length word itself */
  490.  
  491.   if (traceit)
  492.     fprintf(stderr, "Comment, length %ld:\n", (long) length);
  493.  
  494.   while (--length >= 0) {
  495.     ch = jpeg_getc(cinfo);
  496.     if (traceit) {
  497.       /* Emit the character in a readable form.
  498.        * Nonprintables are converted to \nnn form,
  499.        * while \ is converted to \\.
  500.        * Newlines in CR, CR/LF, or LF form will be printed as one newline.
  501.        */
  502.       if (ch == '\r') {
  503.     fprintf(stderr, "\n");
  504.       } else if (ch == '\n') {
  505.     if (lastch != '\r')
  506.       fprintf(stderr, "\n");
  507.       } else if (ch == '\\') {
  508.     fprintf(stderr, "\\\\");
  509.       } else if (isprint(ch)) {
  510.     putc(ch, stderr);
  511.       } else {
  512.     fprintf(stderr, "\\%03o", ch);
  513.       }
  514.       lastch = ch;
  515.     }
  516.   }
  517.  
  518.   if (traceit)
  519.     fprintf(stderr, "\n");
  520.  
  521.   return TRUE;
  522. }
  523.  
  524.  
  525. /*
  526.  * The main program.
  527.  */
  528.  
  529. GLOBAL int
  530. main (int argc, char **argv)
  531. {
  532.   struct jpeg_decompress_struct cinfo;
  533.   struct jpeg_error_mgr jerr;
  534. #ifdef PROGRESS_REPORT
  535.   struct cdjpeg_progress_mgr progress;
  536. #endif
  537.   int file_index;
  538.   djpeg_dest_ptr dest_mgr = NULL;
  539.   FILE * input_file;
  540.   FILE * output_file;
  541.   JDIMENSION num_scanlines;
  542.  
  543.   /* On Mac, fetch a command line. */
  544. #ifdef USE_CCOMMAND
  545.   argc = ccommand(&argv);
  546. #endif
  547.  
  548.   progname = argv[0];
  549.   if (progname == NULL || progname[0] == 0)
  550.     progname = "djpeg";        /* in case C library doesn't provide it */
  551.  
  552.   /* Initialize the JPEG decompression object with default error handling. */
  553.   cinfo.err = jpeg_std_error(&jerr);
  554.   jpeg_create_decompress(&cinfo);
  555.   /* Add some application-specific error messages (from cderror.h) */
  556.   jerr.addon_message_table = cdjpeg_message_table;
  557.   jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  558.   jerr.last_addon_message = JMSG_LASTADDONCODE;
  559.   /* Insert custom COM marker processor. */
  560.   jpeg_set_marker_processor(&cinfo, JPEG_COM, COM_handler);
  561.  
  562.   /* Now safe to enable signal catcher. */
  563. #ifdef NEED_SIGNAL_CATCHER
  564.   sig_cinfo = (j_common_ptr) &cinfo;
  565.   signal(SIGINT, signal_catcher);
  566. #ifdef SIGTERM            /* not all systems have SIGTERM */
  567.   signal(SIGTERM, signal_catcher);
  568. #endif
  569. #endif
  570.  
  571.   /* Scan command line to find file names. */
  572.   /* It is convenient to use just one switch-parsing routine, but the switch
  573.    * values read here are ignored; we will rescan the switches after opening
  574.    * the input file.
  575.    * (Exception: tracing level set here controls verbosity for COM markers
  576.    * found during jpeg_read_header...)
  577.    */
  578.  
  579.   file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
  580.  
  581. #ifdef TWO_FILE_COMMANDLINE
  582.   /* Must have either -outfile switch or explicit output file name */
  583.   if (outfilename == NULL) {
  584.     if (file_index != argc-2) {
  585.       fprintf(stderr, "%s: must name one input and one output file\n",
  586.           progname);
  587.       usage();
  588.     }
  589.     outfilename = argv[file_index+1];
  590.   } else {
  591.     if (file_index != argc-1) {
  592.       fprintf(stderr, "%s: must name one input and one output file\n",
  593.           progname);
  594.       usage();
  595.     }
  596.   }
  597. #else
  598.   /* Unix style: expect zero or one file name */
  599.   if (file_index < argc-1) {
  600.     fprintf(stderr, "%s: only one input file\n", progname);
  601.     usage();
  602.   }
  603. #endif /* TWO_FILE_COMMANDLINE */
  604.  
  605.   /* Open the input file. */
  606.   if (file_index < argc) {
  607.     if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
  608.       fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
  609.       exit(EXIT_FAILURE);
  610.     }
  611.   } else {
  612.     /* default input file is stdin */
  613. #ifdef USE_SETMODE        /* need to hack file mode? */
  614.     setmode(fileno(stdin), O_BINARY);
  615. #endif
  616. #ifdef USE_FDOPEN        /* need to re-open in binary mode? */
  617.     if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
  618.       fprintf(stderr, "%s: can't open stdin\n", progname);
  619.       exit(EXIT_FAILURE);
  620.     }
  621. #else
  622.     input_file = stdin;
  623. #endif
  624.   }
  625.  
  626.   /* Open the output file. */
  627.   if (outfilename != NULL) {
  628.     if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
  629.       fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
  630.       exit(EXIT_FAILURE);
  631.     }
  632.   } else {
  633.     /* default output file is stdout */
  634. #ifdef USE_SETMODE        /* need to hack file mode? */
  635.     setmode(fileno(stdout), O_BINARY);
  636. #endif
  637. #ifdef USE_FDOPEN        /* need to re-open in binary mode? */
  638.     if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
  639.       fprintf(stderr, "%s: can't open stdout\n", progname);
  640.       exit(EXIT_FAILURE);
  641.     }
  642. #else
  643.     output_file = stdout;
  644. #endif
  645.   }
  646.  
  647. #ifdef PROGRESS_REPORT
  648.   /* Enable progress display, unless trace output is on */
  649.   if (jerr.trace_level == 0) {
  650.     progress.pub.progress_monitor = progress_monitor;
  651.     progress.completed_extra_passes = 0;
  652.     progress.total_extra_passes = 0;
  653.     progress.percent_done = -1;
  654.     cinfo.progress = &progress.pub;
  655.   }
  656. #endif
  657.  
  658.   /* Specify data source for decompression */
  659.   jpeg_stdio_src(&cinfo, input_file);
  660.  
  661.   /* Read file header, set default decompression parameters */
  662.   (void) jpeg_read_header(&cinfo, TRUE);
  663.  
  664.   /* Adjust default decompression parameters by re-parsing the options */
  665.   file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
  666.  
  667.   /* Initialize the output module now to let it override any crucial
  668.    * option settings (for instance, GIF wants to force color quantization).
  669.    */
  670.   switch (requested_fmt) {
  671. #ifdef BMP_SUPPORTED
  672.   case FMT_BMP:
  673.     dest_mgr = jinit_write_bmp(&cinfo, FALSE);
  674.     break;
  675.   case FMT_OS2:
  676.     dest_mgr = jinit_write_bmp(&cinfo, TRUE);
  677.     break;
  678. #endif
  679. #ifdef GIF_SUPPORTED
  680.   case FMT_GIF:
  681.     dest_mgr = jinit_write_gif(&cinfo);
  682.     break;
  683. #endif
  684. #ifdef PPM_SUPPORTED
  685.   case FMT_PPM:
  686.     dest_mgr = jinit_write_ppm(&cinfo);
  687.     break;
  688. #endif
  689. #ifdef RLE_SUPPORTED
  690.   case FMT_RLE:
  691.     dest_mgr = jinit_write_rle(&cinfo);
  692.     break;
  693. #endif
  694. #ifdef TARGA_SUPPORTED
  695.   case FMT_TARGA:
  696.     dest_mgr = jinit_write_targa(&cinfo);
  697.     break;
  698. #endif
  699.   default:
  700.     ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
  701.     break;
  702.   }
  703.   dest_mgr->output_file = output_file;
  704.  
  705.   /* Start decompressor */
  706.   jpeg_start_decompress(&cinfo);
  707.  
  708.   /* Write output file header */
  709.   (*dest_mgr->start_output) (&cinfo, dest_mgr);
  710.  
  711.   /* Process data */
  712.   while (cinfo.output_scanline < cinfo.output_height) {
  713.     num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
  714.                     dest_mgr->buffer_height);
  715.     (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
  716.   }
  717.  
  718. #ifdef PROGRESS_REPORT
  719.   /* Hack: count final pass as done in case finish_output does an extra pass.
  720.    * The library won't have updated completed_passes.
  721.    */
  722.   progress.pub.completed_passes = progress.pub.total_passes;
  723. #endif
  724.  
  725.   /* Finish decompression and release memory.
  726.    * I must do it in this order because output module has allocated memory
  727.    * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
  728.    */
  729.   (*dest_mgr->finish_output) (&cinfo, dest_mgr);
  730.   jpeg_finish_decompress(&cinfo);
  731.   jpeg_destroy_decompress(&cinfo);
  732.  
  733.   /* Close files, if we opened them */
  734.   if (input_file != stdin)
  735.     fclose(input_file);
  736.   if (output_file != stdout)
  737.     fclose(output_file);
  738.  
  739. #ifdef PROGRESS_REPORT
  740.   /* Clear away progress display */
  741.   if (jerr.trace_level == 0) {
  742.     fprintf(stderr, "\r                \r");
  743.     fflush(stderr);
  744.   }
  745. #endif
  746.  
  747.   /* All done. */
  748.   exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  749.   return 0;            /* suppress no-return-value warnings */
  750. }
  751.